<?php 
/**
 * Created by Sublime
 * User: yinni
 * Date: 2017/09/26
 * Time: 19:37
 */
namespace App\Services\Admin;

use Facades\App\Repositories\Eloquent\CoringRepositoryEloquent;
use Facades\App\Repositories\Eloquent\UserRepositoryEloquent;
use Facades\App\Repositories\Eloquent\MonitorRepositoryEloquent;
use Facades\App\Repositories\Eloquent\Monitor_alarmRepositoryEloquent;
use Facades\App\Repositories\Eloquent\Monitor_alarm_historyRepositoryEloquent;
use Facades\App\Repositories\Eloquent\Room_loopRepositoryEloquent;
use Facades\Yajra\Datatables\Html\Builder;
use App\Traits\DatatableActionButtonTrait;
use App\Http\Controllers\MailController;
use Datatables;
use Exception;
use DB;

class CoringService{
	use DatatableActionButtonTrait;

	protected $module = 'coring'; //模块路由

	protected $indexRoute = 'coring.index'; 

	protected $createRoute = 'coring.create';

	protected $showRoute = 'coring.show';

	protected $editRoute = 'coring.edit';

	protected $destroyRoute = 'coring.destroy';

    // 微信模板消息推送
    protected $appid = 'wx9ad63a20b597ff1f';
    protected $appsecret = 'e37c09ce7f122137bc2066fed909d732';
    protected $access_token = '6YkeUJ9HkhK7z6zHZuuX-VWLwSqQf-Du8Ovom8aK1SxHfhmmixhUsHIG0FA4nNJ3pEVYvQDRDbc4HbhU71LMVeQNjzobcSJchh0f3O28wDcGlM7IZv5ITAP57gtlAyJ9VUKgAHAMLB';
    protected $lasttime = 1406469747;

    public function __construct() {
        // 定义当前需使用的数据表
        $this->coring = CoringRepositoryEloquent::all();
        $this->monitor = MonitorRepositoryEloquent::all();
        $this->monitor_alarm = Monitor_alarmRepositoryEloquent::all();
        $this->monitor_alarm_history = Monitor_alarm_historyRepositoryEloquent::all();
        $this->room_loop = Room_loopRepositoryEloquent::all();
        $this->send_mail = new MailController();
       
    }


	/**
	 * 首页
	 * @return array
	 */
	public function index() {
		if(request()->ajax()) {
			return $this->ajaxData();
		}
        $html = Builder::parameters([
            'searchDelay' => 350,
            'language' => [
                'url' => url(getThemeAssets('dataTables/language/zh.json', true))
            ],
            'drawCallback' => <<<Eof
					function() {
				        LaravelDataTables["dataTableBuilder"].$('.tooltips').tooltip( {
				          placement : 'top',
				          html : true
				        });
			        },
Eof
        ])->addIndex(['data' => 'DT_Row_Index', 'name' => 'DT_Row_Index', 'title' => trans('common.number')])
            ->addColumn(['data' => 'core_id', 'name' => 'core_id', 'title' => trans('coring.core_id')])
            ->addColumn(['data' => 'loop_name', 'name' => 'loop_name', 'title' => trans('coring.loop_name')])
            ->addColumn(['data' => 'resi_current', 'name' => 'resi_current', 'title' => trans('coring.resi_current')])
            ->addColumn(['data' => 'cable_temp', 'name' => 'cable_temp', 'title' => trans('coring.cable_temp')])
            ->addColumn(['data' => 'location', 'name' => 'location', 'title' => trans('coring.location')])
            ->addColumn(['data' => 'smoke', 'name' => 'smoke', 'title' => trans('coring.smoke')])
            ->addColumn(['data' => 'fire', 'name' => 'fire', 'title' => trans('coring.fire')])
            ->addAction(['data' => 'near_infrared', 'name' => 'near_infrared', 'title' => trans('coring.near_infrared')]);

            return compact('html');
        }

    /**
     * datatable数据,核心逻辑处理
     * @return mixed
     */
    public function ajaxData() {
        // 取出core表的所有信息
        $alltimeinfo_data = CoringRepositoryEloquent::all();

        // 遍历每条记录进行报警响应数据逻辑处理
        foreach ($alltimeinfo_data as $key => $value) {

            // 根据core_id从monitor表中取出定义表中的每一个回路id
            $temp_core_id = $alltimeinfo_data[$key]['core_id'];

            // 取出当前的温度、明火、烟雾、近红外值
            $temp_tempure = $alltimeinfo_data[$key]['cable_temp'];
            // dump($temp_tempure);die;
            $temp_smoke = $alltimeinfo_data[$key]['smoke'];
            $temp_fire = $alltimeinfo_data[$key]['fire'];
            $temp_near_infrared = $alltimeinfo_data[$key]['near_infrared'];
            $temp_resi_current = $alltimeinfo_data[$key]['resi_current'];

            // 根据当前回路id从room_loop表中取出回路名称、及上级电气室负责人邮箱
            $core_id_all = $this->room_loop->where('loop_id',$temp_core_id)->first();
            $loop_name = $core_id_all['loop_name'];
            $room_id = $core_id_all['room_id'];
            $roomer_email = $core_id_all['roomer_email'];

            // 从测点定义表取出所有测点的id值
            $all_monitor = $this->monitor->pluck('monitor_id')->toArray();

            // 预判当前的实时监测id是否属于测点定义表并进行逻辑处理
            if(in_array($temp_core_id, $all_monitor)) {
                // 针对当前的core_id取出温度的额定值，其余的三项指标进行 0 1判断
                $normal_tempure_array = $this->monitor->where('monitor_id',$temp_core_id)->pluck('cable_temp')->toArray();
                $normal_tempure = $normal_tempure_array[0];

                // 保存判断结果以及返回报警状态至ajax前端
                $result['cable_temp'] = 0;
                $result['fire'] = 0;
                $result['smoke'] = 0;
                $result['near_infrared'] = 0;
                $alarm_status = 0;
                if($normal_tempure <= $temp_tempure) {
                    $result['cable_temp'] = 1;
                    $alarm_status = 1;
                }
                if($temp_fire == 1 ) {
                    $result['fire'] = 1;
                    $alarm_status = 1;
                }
                if($temp_smoke == 1) {
                    $result['smoke'] = 1;
                    $alarm_status = 1;
                }
                if($temp_near_infrared == 1) {
                    $result['near_infrared'] = 1;
                    $alarm_status = 1;
                }
                // 将其添加至ajax返回数组中
                $alltimeinfo_data[$key]['is_tempure_alarm'] = $result['cable_temp'];
                if($alarm_status == 1) {
                    $alltimeinfo_data[$key]['status'] = 2;
                } 

                // 将已发生报警的回路信息更新至到monitor_alarm表，并添加至monitor_alarm_history中
                if($alarm_status == 1) {
                    // 取出当前测点所在monitor_alarm表中的最新记录，检测是否已加入
                    $monitor_alarm_data['start_time'] = date('Y-m-d H:i:s',time());
                    $monitor_alarm_data['mobile_phone'] = 0;
                    if($result['cable_temp'] == 1)  {
                        $monitor_alarm_data['cable_temp'] = 1;
                    }
                    if($result['fire'] == 1) {
                        $monitor_alarm_data['fire'] = 1;
                    }
                    if($result['smoke'] == 1) {
                        $monitor_alarm_data['smoke'] = 1;
                    }
                    if($result['near_infrared'] == 1) {
                        $monitor_alarm_data['near_infrared'] = 1;
                    }
 

                    // 已发生警报的前提下，对比monitor_alarm表报警类型进行邮件发送，monitor_alarm_history记录插入
                    // 邮件发送测试，取出monitor_alarm中整条数据
                    $temp_waiting_record = $this->monitor_alarm
                                        ->where('monitor_id',$temp_core_id)
                                        ->first()->toArray();
                    $record['cable_temp'] = $temp_waiting_record['cable_temp'];
                    $record['fire'] = $temp_waiting_record['fire'];
                    $record['smoke'] = $temp_waiting_record['smoke'];
                    $record['near_infrared'] = $temp_waiting_record['near_infrared'];
                    $record['mobile_phone'] = $temp_waiting_record['mobile_phone'];
                    // dump(($record['cable_temp'] != $result['cable_temp']) || ($record['fire'] != $result['fire']) || ($record['smoke'] != $result['smoke']) ||($record['near_infrared'] != $result['near_infrared']));die;
                    if(($record['cable_temp'] != $result['cable_temp']) || ($record['fire'] != $result['fire']) || ($record['smoke'] != $result['smoke']) ||($record['near_infrared'] != $result['near_infrared']))
                    {
                        // 判断access_token请求超时重新获取
                        if (time() > ($this->lasttime + 7200)) {
                        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->appsecret;
                        $res = $this->http_request($url);
                        $this->access_token = $res['access_token'];
                        $this->lasttime = time();

                        } 
                        // 拼接报警类型
                        if( $result['cable_temp']) $tpl_type1 = '温度 | ';
                        else $tpl_type1 = '';
                        if( $result['smoke']) $tpl_type2 = '烟雾 | ';
                        else $tpl_type2 = '';                        
                        if( $result['fire']) $tpl_type3 = '明火 | ';
                        else $tpl_type3 = '';                        
                        if( $result['near_infrared']) $tpl_type4 = '近红外检测 | ';
                        else $tpl_type4 = '';      
                        $res_tpl_type =  $tpl_type1.$tpl_type2.$tpl_type3.$tpl_type4;                 
                     $data_tpl = [
                            'touser' => 'oL7XN01qwgHYgyQbrBbzGGAQuA4M',    //管理员的OpenID
                            'template_id' => 'BO8Jmcnn-FKLu-k4Q95SPYtDAAdGMCKFRRZ3P2fWT0A',     //模板ID  
                            'data' => [
                                'first' => [
                                    'value' => '电气室负责人：'.$roomer_email,
                                    'color' => '#FF0000',
                                ],
                                'keyword1' => [
                                    'value' => $temp_core_id.'/'.$loop_name,
                                    'color' => '#173177',
                                ],
                                'keyword2' => [
                                    'value' => '[工厂1] [车间1] [工段1] '.$room_id.'电气室',
                                    'color' => '#C4C400',
                                ],
                                'keyword3' => [
                                    'value' => $res_tpl_type,
                                    'color' => '#FF0000',
                                ],
                                // 'keyword4' => [
                                //     'value' => 'xxx',
                                //     'color' => '#173177',
                                // ],
                                // 'keyword5' => [
                                //     'value' => '15062242255',
                                //     'color' => '#173177',
                                // ],
                                'remark' => [
                                    'value' => '尚未处理，请尽快确认！',
                                    'color' => '#008000',
                                ]
                            ]
                        ];  
                     $data_tpl2 = [
                            'touser' => 'oL7XN03sQQHyJF5ByvXogmFBH6Jg',    //管理员的OpenID
                            'template_id' => 'BO8Jmcnn-FKLu-k4Q95SPYtDAAdGMCKFRRZ3P2fWT0A',     //模板ID  
                            'data' => [
                                'first' => [
                                    'value' => '电气室负责人：'.$roomer_email,
                                    'color' => '#FF0000',
                                ],
                                'keyword1' => [
                                    'value' => $temp_core_id.'/'.$loop_name,
                                    'color' => '#173177',
                                ],
                                'keyword2' => [
                                    'value' => '[工厂1] [车间1] [工段1] '.$room_id.'电气室',
                                    'color' => '#C4C400',
                                ],
                                'keyword3' => [
                                    'value' => $res_tpl_type,
                                    'color' => '#FF0000',
                                ],
                                // 'keyword4' => [
                                //     'value' => 'xxx',
                                //     'color' => '#173177',
                                // ],
                                // 'keyword5' => [
                                //     'value' => '15062242255',
                                //     'color' => '#173177',
                                // ],
                                'remark' => [
                                    'value' => '尚未处理，请尽快确认！',
                                    'color' => '#008000',
                                ]
                            ]
                        ]; 
                    $tpl_data = urldecode(json_encode($data_tpl));
                    $tpl_data2 = urldecode(json_encode($data_tpl2));
                    $res_tpl = $this->send_tpl_msg($tpl_data); 
                    $res_tpl = $this->send_tpl_msg($tpl_data2); 
                    // dump($res_tpl);die;

                    $res_update_data = DB::table('monitor_alarm')->where('monitor_id',$temp_core_id)->update(['start_time' => $monitor_alarm_data['start_time'],
                        'status' => 0,'mobile_phone' => 1, 'cable_temp' => $result['cable_temp'],
                        'fire' => $result['fire'],'smoke' => $result['smoke'],
                        'near_infrared' => $result['near_infrared']]);
                    try {
                        $res_email_send = (new MailController())->send($temp_core_id,$loop_name,$result['cable_temp'],$result['fire'],$result['smoke'],$result['near_infrared'],$room_id,$roomer_email);
                    }catch (Exception $e) {
                        // dump($e);die;
                    }

                }
                }else {
                    // $res_two = DB::table('monitor_alarm')->where('monitor_id',$temp_core_id)->update(['status' => 3,'cable_temp' => $result['cable_temp'],
                    //     'fire' => $result['fire'],'smoke' => $result['smoke'],
                    //     'near_infrared' => $result['near_infrared']]); 
                }

            }

        }
        return $alltimeinfo_data;
   //  	return Datatables::of(CoringRepositoryEloquent::all())
			// ->addIndexColumn()
			// ->addColumn('action', function ($permission)
			// {
			// 	return $this->getActionButtonAttribute($permission->id);
			// })
			// ->make(true);
    }

    // 获取当前登录用户管理设备详情，包含设备位置以及设备数
    public function getManagerDevices($uesrname = null) {
        // 为superadmin时，取出所有的测点信息
        $username = auth()->user()->username;
        // 理应从admin_users取出id，从关联user_roles取出管理员角色
        // 时间问题，直接比对，需完善
        if ($username == "superadmin") {
            $count = $this->monitor->count();
            $data['count'] = $count;
            // 表设计问题、应查询room_loop
            $monitor_all = DB::table('monitor')->distinct()->pluck('location'); // 去重获取所有信息
            $data['room_all'] = $monitor_all;
            // 根据关联part_room表取出所有测点工段位置
            $data['part_all'] = DB::table('part_room')->distinct()->pluck('part_name');
            // 根据关联shop_part表取出所有的测点车间位置
            $data['shop_all'] = DB::table('shop_part')->distinct()->pluck('shop_name');
            return $data;
            // dump($data);die;
        }
    }

    /**
     * 实时监测json数据
     * @return json
     */
    public function ajaxJsonData() {
        return CoringRepositoryEloquent::all();
    }

    /**
     * 重写datatable action按钮
     * @param $id
     * @return string
     */
    public function getActionButtonAttribute($id)
    {
        return $this->getShowActionButtion($id).
            $this->getEditActionButton($id).
            $this->getDestroyActionButton($id);
    }

    /**
     * 查看
     * @param $id
     * @return array|\Illuminate\Http\RedirectResponse
     */
    public function show($id)
    {
        // try {
        //     $user = UserRepositoryEloquent::with(['userPermissions', 'roles'])->find(decodeId($id, $this->module));
        //     $permissions = $this->getAllPermissions();
        //     $roles = $this->getAllRole();
        //     return compact('user', 'permissions', 'roles');
        // } catch (Exception $e) {
        //     flash(trans('common.find_error'), 'danger');
        //     return redirect()->route($this->indexRoute);
        // }
    }

    // 发送模板消息
    public function send_tpl_msg($data) {
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
        $res = $this->http_request($url,$data);
        return $res;
    }

    // 向微信客户端发起http POST请求
    // 包含access_token以及模板消息的发送
    public function http_request($url, $data = null) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // 发送模板消息
        if (!empty($data)) {
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
        }
        // token值的获取
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        // curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $out = curl_exec($ch);
        curl_close($ch);
        return  json_decode($out,true);     
    }


}